
package com.segment.dcore.dubbo.shutdown;

import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.registry.support.AbstractRegistryFactory;
import com.segment.dcore.servlet.filter.ServletServiceInvokeFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * LaLaDestroy
 *
 * Created by huapeng.hhp on 2017/4/12.
 */
@Component
public class LaLaDestroy {
	/** LOGGER for LalaDestroy */
	private static final Logger LOGGER = LoggerFactory.getLogger(ServletServiceInvokeFilter.class);

	@PreDestroy
	public void shutdown() {
		LOGGER.info("destroy dubbo service client ....");
		try {
			AbstractRegistryFactory.destroyAll();
			ProtocolConfig.destroyAll();
		} catch (Exception e) {
			LOGGER.error("", e);
		}
		LOGGER.info("destroy dubbo NettyClient ....");
		try {
			final Class<?> clazz = Class.forName("com.alibaba.dubbo.remoting.transport.netty.NettyClient");
			Field field = clazz.getDeclaredField("channelFactory");
			field.setAccessible(true);
			Object channelFactory = field.get(null);
			Method method = channelFactory.getClass().getMethod("releaseExternalResources");
			method.invoke(channelFactory);
		} catch (Exception e) {
			LOGGER.error("", e);
		}
		try {
			Thread.sleep(2000);
		} catch (Exception e) {
			LOGGER.error("", e);
		}
	}
}
